<template>
  <div class="main app-containerA">
    <div class="openOrder">
      <!-- 顶部查询表单 -->
      <div class="openOrderTop">
        <el-form ref="searchForm" :model="queryParam" :inline="true" size="mini" label-position="right">
          <el-form-item label="合同编号：">
            <el-input maxLength="20" placeholder="请输入" v-model="queryParam.contractNo" style="width: 200px" clearable></el-input>
          </el-form-item>
          <el-form-item label="金融服务状态：">
            <el-select placeholder="请选择" clearable v-model="queryParam.fsStatus" filterable>
              <el-option v-for="(item, index) in statusList" :key="index" :value="item.rvLowValue" :label="item.rvCmeaning"></el-option>
            </el-select>
          </el-form-item>
          <el-form-item label="托运人：">
            <el-input maxLength="20" placeholder="请输入" v-model="queryParam.cmtPartyA" style="width: 200px" clearable></el-input>
          </el-form-item>
          <el-form-item label="签订时间：">
            <el-date-picker maxLength="20" placeholder="请输入开始时间" v-model="queryParam.signTimeStart" style="width: 200px" clearable></el-date-picker>
            -
            <el-date-picker maxLength="20" placeholder="请输入结束时间" v-model="queryParam.signTimeEnd" style="width: 200px" clearable></el-date-picker>
          </el-form-item>
          <el-button type="primary" @click="searchList">查询</el-button>
        </el-form>
      </div>
      <div class="openTitle">合同列表</div>
      <!-- 按钮组 -->
      <div class="btn">
        <buttonName @clickEvent="clickEvent"></buttonName>
      </div>
      <div class="openOrderBox" ref="tableH" style="height: 100%">
        <el-table
          border
          ref="contractTableRef"
          :height="maxHeight"
          :data="contractList"
          @row-click="contractTableRowClick"
          @selection-change="contractTableSelectChange"
          :row-style="contractTableRowStyle"
        >
          <el-table-column align="center" type="selection" fixed="left"></el-table-column>
          <el-table-column align="center" label="序号" width="55" type="index"></el-table-column>
          <el-table-column align="center" prop="fsStatus" label="申请状态" show-overflow-tooltip width="100"></el-table-column>
          <el-table-column align="center" prop="cmtSigningTime" label="签订时间" show-overflow-tooltip width="165"></el-table-column>
          <el-table-column align="center" prop="cmtContractNo" label="合同编号" show-overflow-tooltip width="165"></el-table-column>
          <el-table-column align="center" prop="cmtContractName" label="合同名称" show-overflow-tooltip width="200"></el-table-column>
          <el-table-column align="center" prop="fsAmount" label="提前结算金额" width="120" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="fsInterest" label="利息" width="100" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="fsLoanTime" label="放款时间" width="200" show-overflow-tooltip></el-table-column>
          <el-table-column align="center" prop="fsAuditOpinion" label="审核意见" show-overflow-tooltip></el-table-column>
        </el-table>
        <div class="block">
          <el-pagination
            ref="pagination"
            class="pagination"
            small
            background
            @size-change="handleSizeChange"
            @current-change="handleCurrentChange"
            :current-page="Pagination.currentPage"
            :page-sizes="Pagination.pageSizeList"
            :page-size="Pagination.PageSize"
            :layout="Pagination.layout"
            :total="Pagination.total"
          ></el-pagination>
        </div>
      </div>
    </div>

    <financialDialog :show="financialDialog.show" :title="financialDialog.title" @close="financialDialog.show = false"></financialDialog>

    <finaccial-upload
      :show="uploadDialog.show"
      :title="uploadDialog.title"
      :file-list="fileList"
      :history-file-list="historyFileList"
      :show-template-button="true"
      @uploadClose="uploadClose"
      @doCommit="doCommit"
    ></finaccial-upload>

    <el-dialog
      v-el-drag-dialog
      ref="dialog"
      width="800px"
      :modal-append-to-body="false"
      :close-on-click-modal="false"
      :close-on-press-escape="false"
      :visible.sync="trialCalculationDialog.show"
      :title="trialCalculationDialog.title"
      @close="trialCalculationDialogClose"
    >
      <el-form :model="trialCalculationDialog.formData" ref="trialCalculationDialogFormRef" size="mini" label-position="right" label-width="120px">
        <el-row>
          <el-col :span="10">
            <el-form-item label="预计止息时间：">
              <el-date-picker
                style="width: 200px"
                v-model="trialCalculationDialog.formData.endTime"
                format="yyyy年MM月dd日"
                placeholder="请选择"
              ></el-date-picker>
            </el-form-item>
          </el-col>
          <el-col :span="10">
            <el-form-item label="预计付款时间：">
              <el-date-picker
                style="width: 200px"
                v-model="trialCalculationDialog.formData.payTime"
                format="yyyy年MM月dd日"
                placeholder="请选择"
              ></el-date-picker>
            </el-form-item>
          </el-col>
        </el-row>
        <el-row>
          <el-col :span="18">
            <el-form-item label="预计金额：">
              <el-input style="width: 300px" disabled v-model="trialCalculationAmount"></el-input>
            </el-form-item>
          </el-col>
        </el-row>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button size="mini" type="primary" @click="trialCalculationDialog.show = false">关 闭</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
import paginationMixin from '@/mixins/pagination'
import resizeMixin from '@/mixins/resize'
import isAuth from '@/mixins/buttonAuth'
import buttonName from '@/components/buttonName/button-name'
import financialService from '@/request/cstManagement/financialService'
import financialDialog from '@/views/cstManagement/twoCstManagement/financialService/financialDialog'
import { getRefCodesByType } from '@/request/dropDown'
import finaccialUpload from './finaccial-upload'
export default {
  name: 'router.openOrderManage',
  mixins: [resizeMixin, paginationMixin, isAuth],
  data() {
    return {
      trialCalculationDialog: {
        show: false,
        title: '',
        formData: {
          amount: 0, // 结算金额
          endTime: null, // 止息时间
          payTime: null, // 付款时间
          result: 0, // 结果
          row: {},
        },
      },
      uploadDialog: {
        show: false,
        title: '',
      },
      contractList: [], // 合同列表
      selectChangeList: [], // 选中的数据
      financialDialog: {
        show: false,
        title: '',
      },
      historyFileList: [], // 历史上传文件列表
      fileList: [], // 上传文件的列表
      delFileList: [], // 删除文件的列表
      maxHeight: -1,
      itemHeight: -1,
      queryParam: {
        contractNo: '', // 合同编号
        cmtPartyA: '', // 托运人
        signTimeStart: undefined, // 合同签订开始时间
        signTimeEnd: undefined, // 合同签订结束时间
        fsStatus: '', // 提交状态
      },
      statusList: [], // 状态列表
    }
  },
  computed: {
    trialCalculationAmount() {
      if (this.trialCalculationDialog.formData.payTime && this.trialCalculationDialog.formData.endTime) {
        const time = (this.trialCalculationDialog.formData.endTime.getTime() - this.trialCalculationDialog.formData.payTime.getTime()) / (1000 * 60 * 60 * 24)
        if (time <= 0) {
          return 0
        }
        return Math.round(((this.trialCalculationDialog.formData.amount * 100) / 8).accMul(time / 360) * 100) / 100
      } else {
        return 0
      }
    },
  },
  components: {
    buttonName,
    financialDialog,
    finaccialUpload,
  },
  created() {
    this.resize = () => {
      this.maxHeight = this.$refs.tableH.offsetHeight - 50
    }
  },
  mounted() {
    this.getStatusList()
    this.searchList()
  },
  methods: {
    contractTableRowStyle({ row }) {
      if (this.selectChangeList.includes(row)) {
        return {
          background: '#5786ee',
        }
      }
    },
    clickEvent({ mdlCode }) {
      if (mdlCode === 'Introduction') {
        this.introduction()
      }
      if (mdlCode === 'commit') {
        this.commit()
      }
      if (mdlCode === 'cancel') {
        this.cancel()
      }
      if (mdlCode === 'trialCalculation') {
        this.trialCalculation()
      }
    },
    getStatusList() {
      getRefCodesByType('金融服务状态').then(res => {
        this.statusList = res.data
      })
    },
    getList(index, size, updateTotal) {
      financialService
        .queryContractListFinancial(
          Object.assign(
            {
              index,
              size,
            },
            this.queryParam
          )
        )
        .then(res => {
          updateTotal(res.total)
          this.contractList = res.data
        })
    },
    // 服务介绍
    introduction() {
      this.financialDialog.show = true
      this.financialDialog.title = '简介'
    },
    // 服务提交
    commit() {
      if (!this.selectChangeList.length) {
        this.$message.error({
          showClose: true,
          message: '至少选择一项',
        })
        return
      }
      const ids = []
      for (let item of this.selectChangeList) {
        if (['TG', 'YTJ'].includes(item.fsStatusCode)) {
          this.$message.error({
            showClose: true,
            message: `${item.cmtContractNo}重复提交`,
          })
          return
        }
        if (item.fsStatusCode === 'SHJJ') {
          ids.push(item.fsId)
        }
      }
      // 重复提交的情况下需要显示历史上传文件
      if (ids.length) {
        financialService
          .queryAnnexArray({
            annex: Array.from(new Set(ids)).map(item => {
              return {
                aPubId: item,
                aModule: 'JR',
              }
            }),
          })
          .then(res => {
            this.historyFileList = res.data.map(item => {
              return {
                name: item.aName,
                url: item.aPath,
                history: true,
                aId: item.aId,
              }
            })
            this.fileList = [].concat(this.historyFileList)
          })
      }
      this.uploadDialog.show = true
      this.uploadDialog.title = '添加附件'
    },

    // 服务取消
    cancel() {
      if (!this.selectChangeList.length) {
        this.$message.error({
          showClose: true,
          message: '至少选择一项',
        })
        return
      }
      if (this.selectChangeList.filter(item => item.fsStatusCode === 'YTJ').length !== this.selectChangeList.length) {
        this.$message.error({
          showClose: false,
          message: '请选择已提交的合同',
        })
        return
      }
      financialService
        .review({
          ids: this.selectChangeList.map(item => item.fsId),
          status: '',
        })
        .then(() => {
          this.$message.success('撤回成功')
          this.refreshList()
        })
    },

    contractTableRowClick(val) {
      this.$refs['contractTableRef'].toggleRowSelection(val)
    },
    contractTableSelectChange(val) {
      this.selectChangeList = val
    },

    trialCalculation() {
      if (this.selectChangeList.length === 0) {
        this.$message.error('请选择一项')
        return
      }
      if (this.selectChangeList.length > 1) {
        this.$message.error('只能选择一项查看')
        return
      }
      this.trialCalculationDialog.show = true
      this.trialCalculationDialog.title = '费用试算'
      this.trialCalculationDialog.formData.row = this.selectChangeList[0]
      this.trialCalculationDialog.formData.amount = this.selectChangeList[0].fsAmount
    },
    trialCalculationDialogClose() {
      this.trialCalculationDialog.formData.payTime = null
      this.trialCalculationDialog.formData.endTime = null
      this.trialCalculationDialog.formData.row = {}
    },
    doCommit() {
      const data = new FormData()
      const historyFileNames = this.historyFileList.map(item => item.aName)
      for (let file of this.fileList) {
        if (historyFileNames.includes(file.name)) {
          continue
        }
        data.append('files', file.raw)
      }
      data.append(
        'data',
        JSON.stringify(
          this.selectChangeList.map(item => {
            return {
              fsDptId: this.$store.state.user.DPTID_DX_H,
              fsFltId: this.$store.state.user.FLT_UUID_DX_H,
              fsCmtId: item.cmtId,
              fsStatus: 'YTJ',
              fsCreator: this.$store.state.user.USR_CODE_DX_H,
              fsAmount: item.fsAmount,
              fsWabId: item.wabId,
              fsIsDel: '0',
            }
          })
        )
      )
      financialService.commitFinancialRequest(data).then(() => {
        this.$message.success({
          showClose: true,
          message: '提交成功',
        })
        this.uploadClose()
      })
    },
    uploadClose() {
      this.historyFileList = []
      this.fileList = []
      this.uploadDialog.show = false
      this.refreshList()
    },
  },
}
</script>

<style lang="scss" scoped>
.app-containerA {
  padding: 1rem 2rem;
  background-color: #fff;
}

.openOrder {
  width: 100%;
  height: calc(100% - 9rem);
  padding-left: 10px;
  padding-top: 10px;
}

.openTitle {
  font-size: 16px;
}

.btn {
  padding-top: 10px;
  padding-bottom: 10px;
}

::v-deep .splitter-pane-resizer.horizontal {
  margin-top: -15px;
}
</style>
